<?php
namespace app\index\controller;

use app\common\controller\Frontend;
use think\Session;
use think\helper\Time;
use app\admin\model\TracePosition;
use app\admin\model\TraceRecord;
use app\admin\model\Student;
use app\admin\model\Teacher;

class Trace extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'weiui';
    protected $model = null;
    protected $re_model = null;


    public function _initialize()
    {
        $title = '学生行动轨迹跟踪上报';
        parent::_initialize();
        $this -> assign('pageTitle',$title);
        $this->model = new TraceRecord();
        $this->re_model = new TracePosition();
    }


    public function index($ids)
    {
        // $ids = strtoupper($ids);
        $row = $this->re_model->where(['number'=>strtoupper($ids)])->find();
        // echo $this->re_model->getLastSql();
        if (!$row) {
            $this->error($ids."记录未找到");
        }
        if($this -> request -> isPost()){
            $params = $this->request->post("row/a");
            $params['sid'] = strtoupper($params['sid']);
            $where = [];
            $where['sid']= $params['sid'];
            $where['nickname']= $params['nickname'];
            $params['type'] = 3;
            
            $stu_model = new Student();
            $per_row = $stu_model ->where($where)->find();
            if(!$per_row)
            {
                $tea_model = new Teacher();
                $where['tel'] = $where['sid'];
                unset($where['sid']);
                $per_row = $tea_model ->where($where)->find();

                if($per_row){
                    $params['classes_id'] = $per_row->department_id;
                    $params['classes_name'] = $per_row->department->name;
                    $params['college_id'] = $per_row->department->college_id;
                    $params['type'] = 1;
                    $params['nickname'] = $per_row->nickname;
                }
            }else{
                $params['classes_id'] = $per_row->classes_id;
                $params['classes_name'] = $per_row->classes->name;
                $params['college_id'] = $per_row->classes->college_id;
                $params['type'] = 2;
                $params['nickname'] = $per_row->nickname;
            }
            
            
            if($per_row && $per_row->classes->college)
                $params['college_name'] = $per_row->classes->college->name;
            $res = $this->model->allowField(true)->save($params);
            if($res)
              return $this->success(date("Y-m-d H:i:s")."{$params['nickname']}在{$row['name']}扫码成功!'");
            else
              return $this->success('地点打卡错误');
        }
        $this->assign('row',$row);

        return $this -> fetch();
    }
}
